const express = require("express")
/* const jwt = require('jsonwebtoken'); */
/* const bcrypt = require('bcryptjs'); */
const adminUser = require("../model/adminUser")
const log = require("../middleware/log")
const { resSuccess, resErr } = require("../public/tip.js")

const loginApp = express()
// 登录
loginApp.post("/login", async (req, res) => {
  try {
    if (req.body) {
      const { username, password } = req.body
      const admin = await adminUser.findOne(username, password)
      if (admin.length > 0) {
        res.send({ ...resSuccess, msg: "登录成功" })
        return
      }
      res.send({ ...resErr, msg: "账号密码错误" })
    }
    /* const passwordMatch = await bcrypt.compare(password, admin.password);
      if (!passwordMatch) {
        return res.status(401).json({ error: 'Unauthorized' });
      } 
      // 身份验证成功，生成JWT Token
      const payload = { username };
      const secretKey = config.secretKey; // 替换为你自己的密钥
      const options = { expiresIn: '1h' }; // 可根据需求设置过期时间
      const token = jwt.sign(payload, secretKey, options);
      // 返回Token给客户端
      res.json({ success: true, token });*/
  } catch (error) {
    console.error(error)
    res.send({ ...resErr, msg: "账号密码错误" })
  }
})

// 获取卖家统计Cookie
loginApp.get("/sellerCookie", async (req, res) => {
  let { pageNum, pageSize } = req.query
  pageSize = Number(pageSize)
  const currentPage = (Number(pageNum) - 1) * pageSize
  try {
    const cookie = await adminUser.findAllCookie(currentPage, pageSize)
    res.send({ ...resSuccess, data: cookie })
  } catch {
    res.send({ ...resErr })
  }
})

// 保存卖家账号Cookie
loginApp.post("/saveSellerCookie", async (req, res) => {
  if (req.body) {
    const { cookie, id, username, password, expiration_time, update_time, crea_time } = req.body
    if (id > 0) {
      const result = await adminUser.updateCookie(cookie, username, password, expiration_time, id, update_time)
      res.send(resSuccess)
    } else {
      const result = await adminUser.addCookie(cookie, username, password, expiration_time, update_time, crea_time)
      res.send(resSuccess)
    }
  } else {
    res.send(resErr)
  }
})

// 删除卖家账号Cookie
loginApp.post("/removeSellerCookie", async (req, res) => {
  if (req.body) {
    const { id } = req.body
    const result = await adminUser.removeCookie(id)
    res.send(resSuccess)
  } else {
    res.send(resErr)
  }
})

module.exports = loginApp
